'use strict';

var app = angular.module("myApp", ['ui.bootstrap', 'ui.bootstrap.treeview2', 'ui.select2']);
// const app = angular.module("myApp",['ui.bootstrap']);

var treeViewTemplate = '\n<tree-view ng-if="graphTree != null && graphTree.g != null" tree-service="graphTree" node-label="text"></tree-view>\n';

app.controller("manageController", ['$scope', '$compile', '$filter', '$uibModal', function ($scope, $compile, $filter, $uibModal) {
    $scope.toJSON = function (val) {
        return angular.toJson(val, true);
    };

    FaultNode.loadFaults();
    $scope.allFaults = FaultNode.faults;
    $scope.faults = [];

    $scope.fault_prop = function (fault) {
        // return fault.features.map(f=>f.frequency / f.quantum).reduce((x,y)=>x>y?x:y,0);
        return 1 - fault.features.map(function (f) {
            return f.frequency / f.quantum;
        }).map(function (x) {
            return 1 - x;
        }).reduce(function (x, y) {
            return x * y;
        }, 1);
    };
    $scope.toTimeString = function (timestamp) {
        return moment(parseInt(timestamp)).format('lll');
    };
    $scope.loadFaults = function () {
        $.get('http://127.0.0.1:8080/faults', function (data) {
            console.info("故障加载为：", data);
            var session = neo4jService.getSession();

            $scope.faults = data.map(function (fault_features) {
                var length = fault_features.length;
                var first = fault_features[0];
                var fault = FaultNode.faults.find(function (f) {
                    return f.id == first.fault_id;
                });

                return {
                    fault: fault,
                    features: fault_features,
                    featureNodes: {},
                    checkedReason: [],
                    fault_state: 0
                };
            });

            var _loop = function _loop(i) {
                Promise.all($scope.faults[i].features.map(function (fitem) {
                    return session.run('start n=node(' + fitem.feature_id + ') RETURN n');
                })).then(function (features) {
                    for (var k = 0; k < features.length; k++) {
                        var feature = MyNode.fromNeo4jNode(features[k].records[0].get("n"));
                        $scope.faults[i].featureNodes[feature.id] = feature;
                    }
                }).then(function () {
                    return session.run('start n=node(' + $scope.faults[i].fault.id + ') match (n)-[*]->(m:Reason) RETURN m');
                }).then(function (reasons) {
                    $scope.faults[i].reasons = reasons.records.map(function (r) {
                        return MyNode.fromNeo4jNode(r.get("m"));
                    });
                    $.get('http://127.0.0.1:8080/reason/' + $scope.faults[i].fault.id, function (data) {
                        $scope.faults[i]["reason_map"] = data;
                        $scope.$apply();
                    });
                });
            };

            for (var i = 0; i < $scope.faults.length; i++) {
                _loop(i);
            }
        });
    };

    $scope.changeState = function (ft, state) {
        ft.fault_state = state;
    };

    $scope.train = function (ft) {
        if (ft.checkedReason.length !== 0 && confirm("确认该故障成立？")) {
            console.info(ft);
            alert("wait");
            $.get('http://127.0.0.1:8080/train/' + ft.fault.id, {
                features: JSON.stringify(ft.features.map(function (f) {
                    return f.feature_id;
                })),
                reasons: JSON.stringify(ft.checkedReason)
            }, function (data) {
                console.info("自学习完成：", data);

                $scope.loadFaults();
            });
        }
    };

    $scope.unsure = function (ft) {
        if (confirm("确认该故障不成立？")) {
            console.info(ft);
            $.get('http://127.0.0.1:8080/clear/' + ft.fault.id, function (data) {
                $scope.loadFaults();
            });
        }
    };

    $scope.submitAll = function () {
        var uncheckedFaults = $scope.faults.filter(function (ft) {
            return ft.fault_state == 1 && ft.checkedReason.length == 0;
        });
        if (uncheckedFaults.length > 0) {
            var msg = uncheckedFaults.map(function (ft) {
                return ft.fault.name;
            }).join(",");
            alert('\u4EE5\u4E0B\u6545\u969C"' + msg + '"\u672A\u9009\u62E9\u54EA\u4E9B\u539F\u56E0\u6210\u7ACB\uFF0C\u8BF7\u9009\u62E9\u540E\u518D\u63D0\u4EA4\uFF01\uFF01\uFF01');
        } else {
            if (confirm("确认对以上内容提交？")) {
                Promise.all($scope.faults.filter(function (ft) {
                    return ft.fault_state != 0;
                }).map(function (ft) {
                    return new Promise(function (resolve, reject) {
                        if (ft.fault_state == 1) {
                            $.get('http://127.0.0.1:8080/train/' + ft.fault.id, {
                                features: JSON.stringify(ft.features.map(function (f) {
                                    return f.feature_id;
                                })),
                                reasons: JSON.stringify(ft.checkedReason)
                            }, function (data) {
                                resolve(data);
                            });
                        } else {
                            $.get('http://127.0.0.1:8080/clear/' + ft.fault.id, function (data) {
                                resolve(data);
                            });
                        }
                    });
                })).then(function (data) {
                    console.info(data);
                    $scope.loadFaults();
                });
            }
        }
    };

    $scope.isSelected = function (ft, reasonId) {
        return ft.checkedReason.indexOf(reasonId) >= 0;
    };

    $scope.updateSelection = function ($event, ft, reasonId) {
        var checkbox = $event.target;
        if (checkbox.checked) {
            //新选中，添加reasonId 到 ft.checkedReason中
            ft.checkedReason.push(reasonId);
        } else {
            //取消选择，移除
            var idx = ft.checkedReason.indexOf(reasonId);
            ft.checkedReason.splice(idx, 1);
        }
    };
}]);
